package com.dmyang.p2pchat.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.dmyang.p2pchat.bean.Message;
import com.dmyang.p2pchat.bean.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 对数据库p2pchat中的chatcontent表进行crud操作
 * Created by brss on 2017/11/3.
 */

public class ChatContentDao {
    private MySqlliteOpenHelper mySqlliteOpenHelper;

    public ChatContentDao(Context context) {
        mySqlliteOpenHelper = new MySqlliteOpenHelper(context, "p2pchat", null, 1);
    }

    public void add(Message message) {
        SQLiteDatabase db = mySqlliteOpenHelper.getReadableDatabase();
        String formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(message.getDate());
        db.execSQL("insert into chatcontent(ipandport,nickname,date,content) values(?,?,?,?);", new Object[]{message.getIpAndPort(),message.getNickname(),formatDate,message.getContent()});
        db.close();
    }

    public void delete(String nickname) {
        SQLiteDatabase db = mySqlliteOpenHelper.getReadableDatabase();
        db.execSQL("delete from chatcontent where nickname='?'", new Object[]{nickname});
        db.close();
    }

    public List queryByIpAndPort(String theIpAndPort) {
        SQLiteDatabase db = mySqlliteOpenHelper.getReadableDatabase();
        String[] strings = new String[1];
        strings[0] = theIpAndPort;
        Cursor cursor = db.rawQuery("select * from chatcontent where ipandport=?;",strings);//无条件查询
        //解析cursor的数据
        List chatList = new ArrayList();
        if (cursor!=null && cursor.getCount()>0){//判断cursor中是否有数据
            while (cursor.moveToNext()){
                //数据库的顺序：id,ipandport,nickname,date,content
                int id = cursor.getInt(0);
                //String ipAndPort = cursor.getString(1);
                String nickname = cursor.getString(2);
                String date = cursor.getString(3);
                String content = cursor.getString(4);

                //把日期字符串转换成日期对象
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date dateObj = null;
                try {
                    dateObj = dateFormat.parse(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                Message message = new Message(theIpAndPort,dateObj,nickname,content);
                chatList.add(message);
                //System.out.println("id:"+id+" username:"+username+" ip"+ip+" port:"+port);
            }
            cursor.close();
        }
        db.close();
        return chatList;
    }

}
